<template>
  <div>
    <!-- 权限检查 -->
    <div v-if="!hasPermission" class="no-permission">
      <el-result icon="warning" title="权限不足" sub-title="您没有访问此页面的权限">
        <template #extra>
          <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
        </template>
      </el-result>
    </div>

    <div v-else>
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="用户名">
          <el-input v-model="search.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="search.role" placeholder="角色">
            <el-option label="全部" value="" />
            <el-option label="学生" value="STUDENT" />
            <el-option label="教师" value="TEACHER" />
            <el-option label="管理员" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchUsers">搜索</el-button>
        </el-form-item>
        <!-- 只有管理员可以批量导入 -->
        <el-form-item v-if="isAdmin">
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="handleImport"
          >
            <el-button>批量导入</el-button>
          </el-upload>
        </el-form-item>
        <!-- 只有管理员可以新增用户 -->
        <el-form-item v-if="isAdmin">
          <el-button type="success" @click="showAddDialog = true">新增用户</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <!-- 管理员可以编辑所有用户，教师只能查看 -->
            <el-button size="small" @click="viewUser(scope.row)">查看</el-button>
            <el-button v-if="isAdmin" size="small" @click="editUser(scope.row)">编辑</el-button>
            <!-- 只有管理员可以删除，且不能删除自己或其他管理员 -->
            <el-button
                v-if="isAdmin && canDeleteUser(scope.row)"
                size="small"
                type="danger"
                @click="handleDeleteUser(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          :total="total"
          @current-change="fetchUsers"
          @size-change="fetchUsers"
          layout="total, prev, pager, next, sizes"
          :page-sizes="[10, 20, 50]"
      />

      <!-- 新增/编辑用户弹窗 -->
      <el-dialog v-model="showAddDialog" :title="form.id ? '编辑用户' : '新增用户'">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" :disabled="!!form.id" />
          </el-form-item>
          <el-form-item v-if="!form.id" label="密码" prop="password">
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="form.realName" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" :disabled="!isAdmin">
              <el-option label="学生" value="STUDENT" />
              <el-option label="教师" value="TEACHER" />
              <el-option label="管理员" value="ADMIN" />
            </el-select>
          </el-form-item>
          <el-form-item label="学号" prop="studentId">
            <el-input v-model="form.studentId" :disabled="!isAdmin" />
          </el-form-item>
          <el-form-item label="工号" prop="teacherId">
            <el-input v-model="form.teacherId" :disabled="!isAdmin" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status">
              <el-option :value="1" label="正常" />
              <el-option :value="0" label="禁用" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUser">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { pageUsers, importUsers, createUser, updateUser, deleteUser } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'

const store = useStore()
const users = ref([])
const total = ref(0)
const page = ref(1)
const size = ref(10)
const search = reactive({ username: '', role: '' })
const showAddDialog = ref(false)
const formRef = ref()
const form = reactive({
  id: null,
  username: '',
  password: '',
  realName: '',
  role: '',
  studentId: '',
  teacherId: '',
  email: '',
  phone: '',
  status: 1
})

// 权限计算
const currentUser = computed(() => store.state.user.userInfo)
const isAdmin = computed(() => currentUser.value?.role === 'ADMIN')
const isTeacher = computed(() => currentUser.value?.role === 'TEACHER')
const hasPermission = computed(() => isAdmin.value || isTeacher.value)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

function fetchUsers() {
  pageUsers({ page: page.value, size: size.value, ...search }).then(res => {
    if (res.code === 200) {
      users.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  }).catch(() => {
    ElMessage.error('获取用户列表失败')
  })
}

function beforeUpload(file) {
  const isExcel = file.type.includes('excel') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  if (!isExcel) {
    ElMessage.error('请上传Excel文件')
    return false
  }
  return true
}

function handleImport({ file }) {
  const formData = new FormData()
  formData.append('file', file)
  importUsers(formData).then(res => {
    if (res.code === 200) {
      ElMessage.success(`导入成功：${res.success}，失败：${res.fail}`)
      if (res.fail > 0) {
        ElMessage.warning(`失败详情：${res.failMsg}`)
      }
      fetchUsers()
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  }).catch(() => {
    ElMessage.error('导入失败')
  })
}

function submitUser() {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.id) {
        updateUser(form.id, form).then(res => {
          if (res.code === 200) {
            ElMessage.success('更新成功')
            showAddDialog.value = false
            fetchUsers()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        }).catch(error => {
          console.error('更新用户失败:', error)
          ElMessage.error(error.message || '更新失败')
        })
      } else {
        const submitData = { ...form }
        delete submitData.id
        createUser(submitData).then(res => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            showAddDialog.value = false
            fetchUsers()
          } else {
            ElMessage.error(res.message || '新增失败')
          }
        }).catch(error => {
          console.error('创建用户失败:', error)
          // 显示具体的错误信息
          if (error.message) {
            ElMessage.error(error.message)
          } else if (error.response && error.response.data && error.response.data.message) {
            ElMessage.error(error.response.data.message)
          } else {
            ElMessage.error('新增失败，请检查输入信息')
          }
        })
      }
    }
  })
}

function viewUser(row) {
  Object.assign(form, row)
  showAddDialog.value = true
}

function editUser(row) {
  Object.assign(form, row)
  showAddDialog.value = true
}

function canDeleteUser(user) {
  // 不能删除自己
  if (user.id === currentUser.value?.id) return false
  // 不能删除其他管理员
  if (user.role === 'ADMIN') return false
  return true
}

function handleDeleteUser(id) {
  ElMessageBox.confirm('确定删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchUsers()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

onMounted(() => {
  if (hasPermission.value) {
    fetchUsers()
  }
})
</script>

<style scoped>
.no-permission {
  text-align: center;
  padding: 50px;
}
</style>